import math
import gameengine
from logger import log
from storage import Storage
import time

class Object:

	DEAD = -1
	IDLE = 0
	CASTING = 1
	SPEAKING = 2

	def __init__(self, name, x, y, width, height, texture):
		self.name = name
		self.x = x
		self.y = y
		self.tx = None
		self.ty = None
		self.nodeId = Storage().newId()
		self.ms = 75
		self.moveStarted = None
		self._updateSection()
		self.sx = None
		self.sy = None
		self.width = width
		self.height = height
		self.texture = texture
		self.state = Object.IDLE
		self.immortal = False
		self.health = 100
		self._updateSection()

	def setPosition(self, x, y):
		self.x = x
		self.y = y
		self._updateSection()

	def setMoveSpeed(self, ms):
		self.ms = ms

	def _updateSection(self):
		self.sx = (int(self.x) / int(gameengine.SCREEN_WIDTH))
		self.sy = (int(self.y) / int(gameengine.SCREEN_HEIGHT))
#		log('Square: %s %s'%(self.sx, self.sy))

	def _updatePos(self):
		# If there was no move...
		if (self.tx is None) or (self.moveStarted is None):
			# Do nothing
			return

		now = time.time()

		timeMoving = now - self.moveStarted
		distMoved = int(timeMoving * self.ms)
#		print 'moved %s units, time delta is %f = %f - %f'%(distMoved, timeMoving, now, self.moveStarted)
		dx = self.tx - self.x
		dy = self.ty - self.y
		totalDist = math.sqrt(dx*dx + dy*dy)

		# Move finished
		if distMoved > totalDist:
			self.state = Object.IDLE
			self.x = self.tx
			self.y = self.ty
			self.moveStarted = None
			return

		k = distMoved / totalDist
		self.x += int(dx * k)
		self.y += int(dy * k)
		self.moveStarted = now
		self._updateSection()

	def getPos(self):
		self._updatePos()
		return {'x':self.x, 'y':self.y}

	def visible(self, other):
#		self._updatePos()
		other._updatePos()
		if None in [self.sx, self.sy, other.sx, other.sy]:
			return False
		return (abs(self.sx - other.sx) <= 1) and (abs(self.sy - other.sy) <= 1)
